import React, { PropTypes, Component } from 'react'
import fetch from 'isomorphic-fetch'
import { Link } from 'react-router'

import Table from './Table'
import NavLink from './NavLink'
import style from './addStore.css'

import { myAjax, ROOTURL,ROOTURL_MALL } from '../publicAPI/publicAPI'

class MallMember extends Component {
     constructor (props, context) {
     	    super(props, context);

     	    this.state = {
     	    	delete: false,
     	    	deleteId: -1,
     	    	barberData:[],
               requestAll: false
     	    }; // 初始化状态

         this.start = 0;
         this.limit = 10;
	}

	componentWillMount() {
          this.getClerk();
	}

     //获取店员信息
     getClerk() {
          fetch(ROOTURL_MALL +'kabuy/assistant/profile/search.api', {
              method: 'POST',
              mode: 'cors',
              body: JSON.stringify({
                  "where": {
                      "dd": [
                          ["eq", false]
                      ],
                      stActivate: [
                          ['eq', true]
                      ]
                 },
                 start: this.start,
                 limit: this.limit
              })
          }).then(res => {
              if (res.ok) {
                  res.json().then(data => {
                      var data2 = [];
                      for (var k = 0; k < data.length; k++) {
                          if (!(data[k].dd)) {
                              data2.push(data[k]);
                          }
                      }

                      if(data2.length < this.limit) {
                           this.setState({
                                requestAll: true
                           })
                      } else {
                           this.setState({
                                requestAll: false
                           })
                      }
                      if (data2.length == 0){
                           this.setState({
                                requestAll: true
                           })
                           return;
                      }

                      this.getdname(data2);
                  })
              }
          })
     }

	getdname(AccountInfo){
          let IdArray = [];
          let phoneArray = [];
          AccountInfo.map(function(elem, index) {
              IdArray[index] = elem.shopId
          });
          console.log(IdArray);
          for (let i = 0; i < IdArray.length; i++) {
              fetch(ROOTURL_MALL + 'kabuy/pickshop/instance.api?id=' + IdArray[i], {
                  method: 'get',
                  headers: {
                      "Content-type": "application/json; charset=UTF-8"
                  }
              }).then(response => {
                  return response.json()
              }).then(data => {
                  AccountInfo[i].dname = data.name;
                  this.setState({barberData: AccountInfo})

              })
          }

	}
	handlePageClick(e) {//1为下一页，2为上一页
        const _buttonValue = e.target.value

        if(_buttonValue == 1) {
            this.start = this.start + this.limit 

        } else {
            this.start = this.start - this.limit 
        }
        this.getClerk()
    }
	handleDelete(id) {
		this.setState({
			delete: !this.state.delete,
			deleteId: id
		})
	}

	deleteBarber(){
			var _this = this;
			var param = {
				// id:this.state.deleteId
			}
	       var URL1 = ROOTURL_MALL + 'kabuy/assistant/profile/instance.api?id=' + this.state.deleteId;
	       // alert(this.state.deleteId);
	       fetch(URL1,{
	           method: 'DELETE',
	           headers: {
                	"Content-type": "application/json; charset=UTF-8"
             	},
	           body: param
	       }).then(function (res) {
	           if (res.ok){
	               console.log('delete success');
	               var barber = _this.state.barberData;
	               barber.map(function (result,index) {
	                   if(result.id == _this.state.deleteId){
	                       barber.splice(index,1);
	                       _this.setState({
	                           barberData: barber
	                       })
	                   }
	               })

	           }else{
	               console.log(res)
	           }
	       });
	       this.setState({
	           delete: !this.state.delete
	       });
	}

	tHead() {
		var data = [
			{name: "id"},
			{name: "姓名"},
			{name: "userid"},
			{name: "手机号"},
			{name: "所属门店"},
			{name: "操作"}
		];
		const _headArr = [];
		const _width = {
			"0" : "14.6%",
			"1" : "14.8%",
			"2" : "16.3%",
			"3" : "14.9%",
			"4" : "19.7%",
			"5" : "19.7%"
		};
		//_headArr.push(<th style={{width:'5%'}} role="1" key='' onClick={(e) => this.handleSelect(e)}></th>)
		_headArr.push(data.map((item, index) => <th style={{width: _width[index]}} role="1" key={index}>{item.name}</th>))
		return _headArr;
	}

	tBody() {

		return this.state.barberData.map(item => <tr key={item.id}>
			<td>{item.id}</td>
			<td>{item.meta.name}</td>
			<td>{item.userid}</td>
			<td>{item.meta.phone}</td>
			<td>{item.dname}</td>
			<td>
				<span><NavLink  to={`/MallMember/MallMemberEditor/${item.id}`} className="rbtn green">查看</NavLink></span>
				<span style={{marginLeft: "15px"}}><a  className="rbtn red" onClick={() => this.handleDelete(item.id)}>删除</a></span>
			</td>
		</tr>)

	}

     //翻页按钮
     handlePageClick(e) {//1为下一页，2为上一页
               const _buttonValue = e.target.value

               if(_buttonValue == 1) {
                    this.start = this.start + this.limit

               } else {
                    this.start = this.start - this.limit
               }
               this.getClerk();
     }

	render(){
		return (

			<div className="right-wapper ">
			    <div className="rt-wrap">
			        <h2 className="catagory">
			            <Link to={`/MallIndex`}><span className={style['cata-title']}>首页轮播图</span></Link>
			            <Link to={`/MallProductTypeM`}><span className={style['cata-title']}>商品分类管理</span></Link>
			            <Link to={`/MallProductsM`}><span className={style['cata-title']}>商品管理</span></Link>
			            <Link to={`/MallOrderM`}><span className={style['cata-title']}>订单管理</span></Link>
			            <Link to={`/MallStoreM`}><span className={style['cata-title']}>门店管理</span></Link>
			            <Link to={`/MallMember`}><span className={style['cata-title-current']}>门店店员管理</span></Link>
			            <Link to={`/MallStatisticsM`}><span className={style['cata-title']}>商城统计</span></Link>
			            <Link to={`/MallCoupon`}><span className={style['cata-title']}>优惠券管理</span></Link>
			            <Link to={`/MallMember/MallMemberEditor`}>
			                <button className="add-btn" />
			            </Link>
			        </h2>
			        <div style={{margin:'20px 0 10px'}}>


					<h2 className="catagory">
						<span className="cata-title">店员管理</span>
						<button className="next" value="1" style={{display: this.state.requestAll ? "none" : "block"}} onClick={(e) => this.handlePageClick(e)}></button>
						<button className="prev" value="2" style={{display: this.start ? "block" : "none"}} onClick={(e) => this.handlePageClick(e)}></button>
					</h2>

					<Table tHead={this.tHead.bind(this)()} tBody={this.tBody.bind(this)()} />
				</div>
				{ this.state.delete ?
					<div id={style.msgDialog}>
						<div className={style['msgDialog_div']}><h3 id={style['msgDialog_title']}>删除提示？</h3><p id={style['msgDialog_content']}>确认删除？</p>
							<div className={style['msgDialog_button']}>
								<button id={style['msgDialog_yes']} onClick={this.deleteBarber.bind(this)}>确定</button>
								<button id={style['msgDialog_no']} onClick={()=>this.setState({delete: !this.state.delete})}>取消</button>
							</div>
						</div>
					</div> : null}
	    	           </div>
			</div>
		)
	}
}


export default MallMember
